# coding:utf-8
import socket
import time

import paramiko

from app.autojob.models import InitTaskConfig, TaskRecord, InitTaskList
from app.autojob.shell_exec import run_command, is_process_finished, ssh_login


def execute_remote_workflow(host, task_id, create_user, create_cnname):
    """初始化任务异步流程"""
    def task_log_create(node_name, status, exception_item):
        TaskRecord.objects.create(taskType='初始化任务', taskId=task_id, nodeName=node_name, operationUserAccount=create_user,
                                  operationCnName=create_cnname, status=status, exceptionItem=exception_item).save()
        InitTaskList.objects.filter(id=task_id).update(status=status)

    info = InitTaskConfig.objects.all().first()
    if not info:
        task_log_create('初始化中', '初始化异常', '未获取登录用户')
        return False
    username = info.username
    password = info.password
    init_script_path = info.initScriptPath
    bond_script_path = info.bondScriptPath
    init_log_path = info.initLogPath
    bond_log_path = info.bondLogPath

    init_script_name = str(init_script_path).split('/')[-1]
    bond_script_name = str(bond_script_path).split('/')[-1]

    res, ssh = ssh_login(host, username, password)
    if not res:
        task_log_create('初始化中', '初始化异常', 'ssh远程连接失败')
        return False

    try:
        run_command(ssh, f"curl -k -s -L {init_script_path} | bash &")  # 后台运行

        count = 1
        st = False
        while not is_process_finished(ssh, init_script_name):
            time.sleep(5)
            count += count
            if count > 360:
                st = True
                task_log_create('初始化中', '初始化异常', '初始化超时')
                break
        if st:
            return False

        # Step 4: 读取 /tmp/os.log 判断是否有 Fail
        stdout, _ = run_command(ssh, f"cat {init_log_path} | grep 'Fail'")
        if 'Fail' in stdout:
            stdout, _ = run_command(ssh, f"cat {init_log_path} | grep 'Fail'" + " |awk -F '[【】]' '{print $4}'")
            tmp = stdout.split('\n')
            task_log_create('初始化中', '初始化异常', ','.join(tmp))
            return

        task_log_create('网络check中', '网络check中', '')

        # Step 5: Run checkNet.sh
        stdout, _ = run_command(ssh, f"curl -k -s -L {bond_log_path} | bash")
        if 'Fail' in stdout:
            stdout, _ = run_command(ssh, f"cat {bond_log_path} | grep 'Fail'" + " |awk -F '[【】]' '{print $4}'")
            tmp = stdout.split('\n')
            task_log_create('网络check中', '网络check异常', ','.join(tmp))
            return
        task_log_create('初始化完成', '初始化完成', '')

    finally:
        ssh.close()
